package com.sgb.jicai.view.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.qgb.zcore.event.ChooseAreaEvent;
import com.qgb.zcore.event.EventConstant;
import com.sgb.jicai.R;
import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.databinding.FragmentCentralizedMining5Binding;
import com.sgb.jicai.view.activity.FactoryCentralizedActivity;
import com.sgb.jicai.view.activity.JiCaiXuFandQiYeActivity;
import com.sgb.jicai.view.activity.XuFangFaQiActivity;
import com.sgb.jicai.view.adapter.HomeHostVideoAdapter;
import com.sgb.jicai.viewmodel.CentralizedMining5Model;
import com.swgk.core.view.entity.VideoListEntity;
import com.sgb.link.router.PathLogin;
import com.sgb.link.utils.JsonListUtil;
import com.sgb.link.utils.SizeUtils;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.BaseHeightViewPagerFragment;
import com.swgk.core.base.aroute.ARouterStartWebBase;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.jicai.view.activity.JiCaiDaTingActivity;
import com.sgb.jicai.view.activity.MyCenterMyJoinActivity;
import com.sgb.jicai.view.activity.JcChanceListActivity;
import com.sgb.jicai.view.activity.JcMyPriceActivity;
import com.swgk.core.customview.HeightViewPager;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.view.weiget.CountMenuView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 2020-6-04  产品王单：新版本 CentralizedMiningFragment3
 * 2020-7-15 新版本集采首页
 * Description:集采首页
 * Author zhao
 */
public class CentralizedMiningFragment5 extends AppLazyFragment {
    CentralizedMining5Model mModel;
    private FragmentCentralizedMining5Binding mBind;

    private ArrayList<Fragment> mFragments;
    private int mCurIndex;
    private HomeHostVideoAdapter bigHomeHostVideoAdapter;
    private int types;

    public static CentralizedMiningFragment5 newInstance() {
        CentralizedMiningFragment5 fragment = new CentralizedMiningFragment5();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBind = DataBindingUtil.inflate(inflater, R.layout.fragment_centralized_mining5, container, false);
        mModel = new ViewModelProvider(this).get(CentralizedMining5Model.class);
        mModel.setActivity(CentralizedMiningFragment5.this);
        mBind.imgBackTop.setOnClickListener(this);
        mBind.viewMore.setOnClickListener(this);
        return mBind.getRoot();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mBind.swipeRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                loadData();
            }

            @Override
            public void onPullDistance(int distance) {
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "释放立即刷新" : "下拉刷新");
            }
        });
        mBind.swipeRefresh.setHeaderView(createHeaderView());
        initMenuView();
        mFragments = new ArrayList<>();
        mBind.tabLayout.setupWithViewPager(mBind.viewPager);
        mBind.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                mCurIndex = i;
                mBind.scrollview.scrollTo(0, 0);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        if (bigHomeHostVideoAdapter == null) {
            bigHomeHostVideoAdapter = new HomeHostVideoAdapter(getActivity(), null, R.layout.item_jicai_home_video, 1);
        }
        GridLayoutManager linearLayoutManager = new GridLayoutManager(getActivity(), 4);
        mBind.videoList.setLayoutManager(linearLayoutManager);
        mBind.videoList.setAdapter(bigHomeHostVideoAdapter);
        mBind.videoList.setNestedScrollingEnabled(false);
        bigHomeHostVideoAdapter.setOnItemClick(new AdapterOnItemClick<VideoBean>() {
            @Override
            public void onItemClick(VideoBean homeHostVideoEntity, int position) {
                String toJson = JsonListUtil.listToJson(bigHomeHostVideoAdapter.getDatas());
                Log.e("tag字符串",toJson);
                ARouterStartWebBase.starPlaylist("home_jicai",toJson , position, 1);
            }
        });
        updateViews2();
        int screenHeight = SizeUtils.getScreenHeight(getActivity());

        //控制置顶按钮的显示隐藏
        mBind.scrollview.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > screenHeight * 2) {
                    mBind.imgBackTop.setVisibility(View.VISIBLE);
                } else if (scrollY < screenHeight * 2) {
                    mBind.imgBackTop.setVisibility(View.GONE);
                }
            }
        });

        mBind.imgBackTop.setOnClickListener(v -> {
            mBind.scrollview.smoothScrollTo(0, 0);
            mBind.scrollview.scrollTo(0, 0);
        });
    }

    private void initMenuView() {
        mBind.calendarMenuView.initData(getChildFragmentManager(), mModel.getMenuData(), new CountMenuView.OnItemClick() {
            @Override
            public void onItemClick(MenuEntity entity, int position, int num) {
                switch (entity.getName()) {
                    case "集采大厅":
                        JiCaiDaTingActivity.start(getActivity());//新版集采大厅
                        break;
                    case "需方发起":
                        XuFangFaQiActivity.start(getActivity(), "1");
                        break;
                    case "企业专项":
                        XuFangFaQiActivity.start(getActivity(), "2");
                        break;
                    case "汇集采购":
                        JiCaiXuFandQiYeActivity.start(getActivity(), "2");
                        break;
                    case "供方发起":
                        FactoryCentralizedActivity.start(getActivity());
                        break;
                    case "即报即采":
                        JiCaiXuFandQiYeActivity.start(getActivity(), "3");
                        break;
                    case "我的加盟":
                        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            MyCenterMyJoinActivity.start(getActivity());
                        } else {
                            ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                        }
                        break;
                    case "我的报价":
                        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            JcMyPriceActivity.start(getActivity());
                        } else {
                            ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                        }
                        break;
                    case "加盟机遇":
                        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            JcChanceListActivity.start(getActivity(), 2);
                        } else {
                            ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                        }
                        break;
                    case "报价机遇":
                        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            JcChanceListActivity.start(getActivity(), 1);
                        } else {
                            ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                        }
                        break;
                    default:
                        MToast.showToast(getActivity(), "功能开发中");//
                        break;

                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {

        mModel.getVideoList("网站经营", "集采/团购");
    }

    private void loadData() {
        if (mFragments == null || mFragments.size() == 0) {
            hideRefresh();
            onLazyLoad();
            return;
        }
        Fragment fragment = mFragments.get(mCurIndex);
        if (fragment instanceof HomeJiCaiXuFangFragment) {
            ((HomeJiCaiXuFangFragment) fragment).setRefresh();
        }
        if (fragment instanceof HomeJiCaiChangJiaFragment) {
            ((HomeJiCaiChangJiaFragment) fragment).setRefresh();
        }
        if (fragment instanceof HomeJiCaiQiYeFragment) {
            ((HomeJiCaiQiYeFragment) fragment).setRefresh();
        }
    }

    //1.15修改为此
    public void updateViews2() {
        if (mFragments != null && mFragments.size() > 0) {
            return;
        }
        mFragments = new ArrayList<>();
        String[] mTitles = new String[3];
        mTitles[0] = "需方发起";
        mTitles[1] = "供方发起";
        mTitles[2] = "企业专项";
        mFragments.add(HomeJiCaiXuFangFragment.newInstance());
        mFragments.add(HomeJiCaiChangJiaFragment.newInstance());
        mFragments.add(HomeJiCaiQiYeFragment.newInstance());
        RecommendFragmentPagerAdapter mPagerAdapter = new RecommendFragmentPagerAdapter(getChildFragmentManager(), mFragments, mTitles);
        mBind.viewPager.setAdapter(mPagerAdapter);
        if (mBind.viewPager instanceof HeightViewPager) {
            ((HeightViewPager) mBind.viewPager).resetHeight(0);
        }
        mBind.viewPager.setOffscreenPageLimit(1);
        mBind.tabLayout.setupWithViewPager(mBind.viewPager);
        mBind.tabLayout.setTabMode(TabLayout.MODE_FIXED);
        mBind.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                inittabView(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void inittabView(int position) {
        if (mFragments == null || mFragments.size() == 0) {
            return;
        }
        Fragment fragment = mFragments.get(position);
        if (null != fragment && fragment instanceof HomeJiCaiXuFangFragment) {
            ((HomeJiCaiXuFangFragment) fragment).initializePop();
        }
        if (null != fragment && fragment instanceof HomeJiCaiChangJiaFragment) {
            ((HomeJiCaiChangJiaFragment) fragment).initializePop();
        }
        if (null != fragment && fragment instanceof HomeJiCaiQiYeFragment) {
            ((HomeJiCaiQiYeFragment) fragment).initializePop();
        }
    }

    public void hideRefresh() {
        mBind.swipeRefresh.setRefreshing(false);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.view_more) {//分享视频-查看更多
            JiCaiBaseApi.setHomeShareAct();
        }
    }

    private TextView textView;

    private View createHeaderView() {
        @SuppressLint("InflateParams")
        View headerView = LayoutInflater.from(mBind.swipeRefresh.getContext()).inflate(R.layout.super_swipe_refresh_head, null);
        ProgressBar progressBar = headerView.findViewById(R.id.pb_view);
        textView = headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            loadData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void showEmpty() {
        hideRefresh();
    }

    //视频列表信息
    public void setVideoTypeList(VideoListEntity data) {
        if (data == null) return;
        if (data != null && data.getRecords().size() > 0) {
            mBind.llVideo.setVisibility(View.VISIBLE);
            bigHomeHostVideoAdapter.setDatas(data.getRecords());
        } else {
            mBind.llVideo.setVisibility(View.GONE);
            MToast.showToast(getActivity(), "没有数据信息！");
        }
    }

    class RecommendFragmentPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> mFragments;
        private String[] mTitlestab;

        public RecommendFragmentPagerAdapter(FragmentManager fm, List<Fragment> data, String[] mTitles) {
            super(fm);
            mFragments = data;
            mTitlestab = mTitles;
        }

        @Override
        public Fragment getItem(int position) {
            HeightViewPager heightViewPager = mBind.viewPager;
            BaseHeightViewPagerFragment fragment = (BaseHeightViewPagerFragment) mFragments.get(position);
            fragment.setHeightViewPager(heightViewPager);
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments == null ? 0 : mFragments.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitlestab[position];
        }
    }
}
